const RadioGroupConfig = {
	LIST: 'radio-list',
	ITEM_CLASS: 'radio-item',
	ITEM_INPUT: 'radio-input',
	ITEM_CONTENT: 'radio-content',
	ITEM_INPUT_CUSTOM: 'radio-input-custom',
	ITEM_BOTTM_BTN_BOX: 'radio-bottom-btn-box',
	ITEM_BOTTOM_BTN_OK: 'radio-bottom-btn-ok'
}

class RadioGroup {
	constructor(options = {}) {
		this.data = options.data;
		this.type = options.type || 'radio';
		this.actived = options.actived;
		this.onChange = options.onChange || (() => {});
		this.el = options.el || 'radio-name';
		this.displayElement = document.getElementById(options.el);
		this.confirmBntClass = this.el + '_confirm_btn';
		this.inputClass = this.el + '_input';
		this.panel = null;
		this.selectedValue = [];
		this.selectedNames = [];
		this.createPanel();
		this.addStyles();
		this.initEvents();
	}
	
	reset(){
		this.displayElement.value = '';
		this.actived = [];
		this.selectedValue = [];
		this.selectedNames = [];
		this.createPanel();
	}

	createPanel() {
		if (this.data.length == 0) return;
		const htmlStr = this.data.map((item, index) =>
			this.generateItem(item, index)
		).join('');
		let contentHtml = `<div class="${RadioGroupConfig.LIST}">${htmlStr}</div>`
		this.initBottomPanel(contentHtml);
	}

	initBottomPanel(content) {
		this.panel = new BottomPanel({
			title: '请选择',
			content: content,
			footer: `<footer class="${RadioGroupConfig.ITEM_BOTTM_BTN_BOX}"><button class="btn-primary flex-1 ${this.confirmBntClass}">确定</button></footer>`,
			triggerSelector: '',
			onOpen: () => console.log('面板打开了'),
			onClose: () => console.log('面板关闭了')
		});
	}

	generateItem(item, index) {
		let id = this.el + '_' + item.id;
		let checked = '';

		// 处理初始选中状态
		if (this.type === 'radio') {
			if (Array.isArray(this.actived) && this.actived.includes(index)) {
				checked = 'checked';
				this.selectedValue = [item.id]; // 单选模式初始值
				this.selectedNames = [item.name];
			}
		} else if (this.type === 'checkbox') {
			if (Array.isArray(this.actived) && this.actived.includes(index)) {
				checked = 'checked';
				this.selectedValue.push(item.id);
				this.selectedNames.push(item.name);
			}
		}
		let itemHtml = `<label class="radio-item" data-index="${index}">
						<input type="${this.type}" name="${this.el}" class="${RadioGroupConfig.ITEM_INPUT} ${this.inputClass}" value="${item.id}" id="${id}" data-name="${item.name}" ${checked}/>
						<span class="${RadioGroupConfig.ITEM_INPUT_CUSTOM}"></span>
						<div class="${RadioGroupConfig.ITEM_CONTENT}">${item.name}</div>
					</label>`;
		return itemHtml;
	}

	initEvents() {
		// 在document.body上设置委托
		document.body.addEventListener('click', (e) => {
			const target = e.target.closest(`.${this.confirmBntClass}`);
			if (target) {
				this.handleConfirm();
			}
		});
		// 为单选按钮添加change事件
		document.addEventListener('change', (e) => {
			if (e.target.classList.contains(this.inputClass)) {
				this.handleInputChange(e.target);
			}
		});
	}

	handleInputChange(input) {
		const value = input.value;
		const name = input.dataset.name;
		if (this.type === 'radio') {
			// 单选模式：直接替换选中值
			this.selectedValue = [value];
			this.selectedNames = [name];
			// 单选模式可以立即触发onChange
			this.onChange({
				values: this.selectedValue,
				names: this.selectedNames
			});
		} else if (this.type === 'checkbox') {
			// 多选模式：添加或移除值
			if (input.checked) {
				// 添加选中值
				if (!this.selectedValue.includes(value)) {
					this.selectedValue.push(value);
					this.selectedNames.push(name);
				}
			} else {
				// 移除选中值
				const index = this.selectedValue.indexOf(value);
				if (index > -1) {
					this.selectedValue.splice(index, 1);
					this.selectedNames.splice(index, 1);
				}
			}
			console.log('当前选中:', this.selectedValue);
		}
	}

	handleConfirm() {
		if (this.selectedValue.length == 0) return alert('请先选择一个选项');
		this.onChange({
			values: this.selectedValue,
			names: this.selectedNames
		});
		this.displayElement.value = this.selectedNames.join(',');
		this.close();
	}

	open() {
		this.panel.open()
	}

	close() {
		this.panel.close()
	}

	addStyles() {
		this.styleElement = document.createElement('style');
		this.styleElement.textContent = `
		
		  :root{
			  --primary: #3A7EF0;
			  --input-w-h: 20px;
			  --bg-gray: #f0f2f5;
			  --bg-white: white;
			  --input-radius: 4px;
			  --ripple-color: 77, 171, 247;
			  --ripple-opacity: 0.4;
			  --ripple-duration: 0.6s;
			  --ripple-scale: 2.5;
			  --ripple-timing: cubic-bezier(0.4, 0, 0.2, 1);
		  }
		  
		  .${RadioGroupConfig.LIST} {
		  	display: flex;
		  	flex-direction: column;
		  	gap: 20px;
			font-size: var(--font-size-primary);
		  }
		  
		  .${RadioGroupConfig.ITEM_CLASS} {
		  	display: inline-flex;
		  	align-items: center;
		  	user-select: none;
		  	position: relative;
		  	cursor: pointer;
		  }
		  
		  .${RadioGroupConfig.ITEM_INPUT} {
		  	display: none;
		  	opacity: 0;
		  	width: 0;
		  	height: 0;
		  }
		  
		  .${RadioGroupConfig.ITEM_INPUT_CUSTOM} {
		  	position: relative;
		  	width: var(--input-w-h);
		  	height: var(--input-w-h);
		  	background: var(--bg-white);
		  	margin-right: calc(var(--gap) / 2);
		  	border: 2px solid var(--bg-gray);
		  	transition: all 0.3s ease;
		  	flex-shrink: 0;
		  	will-change: transform, opacity;
		  	backface-visibility: hidden;
		  }
		  
		  .${RadioGroupConfig.ITEM_INPUT}[type="radio"]+ .${RadioGroupConfig.ITEM_INPUT_CUSTOM} {
		  	border-radius: 50%;
		  }
		  
		  .${RadioGroupConfig.ITEM_INPUT}[type="checkbox"]+ .${RadioGroupConfig.ITEM_INPUT_CUSTOM} {
		  	border-radius: var(--input-radius);
		  }
		  
		  .${RadioGroupConfig.ITEM_CONTENT} {
		  	font-family: 'Segoe UI', system-ui, sans-serif;
		  	color: var(--color-black);
			margin-left:var(--gap);
			font-size:14px;
		  }
		  
		  .${RadioGroupConfig.ITEM_INPUT}:checked+ .${RadioGroupConfig.ITEM_INPUT_CUSTOM} {
		  	border-color: var(--primary);
		  }
		  
		  .${RadioGroupConfig.ITEM_INPUT}:checked+.${RadioGroupConfig.ITEM_INPUT_CUSTOM}::before {
		  	content: "";
		  	position: absolute;
		  	top: 50%;
		  	left: 50%;
		  	transform: translate(-50%, -50%);
		  	width: calc(var(--input-w-h) * 0.6);
		  	height: calc(var(--input-w-h) * 0.6);
		  	background: var(--primary);
		  }
		  
		  .${RadioGroupConfig.ITEM_INPUT}:checked+.${RadioGroupConfig.ITEM_INPUT_CUSTOM}::after {
		  	content: "";
		  	position: absolute;
			
		  	top: 50%;
		  	left: 50%;
		  	transform: translate(-50%, -50%);
		  	width: calc(var(--input-w-h) * 0.6);
		  	height: calc(var(--input-w-h) * 0.6);
		  	background: rgba(var(--ripple-color), var(--ripple-opacity));
		  	transform: translate(-50%, -50%) scale(0);
			z-index: -1;
			pointer-events: none;
		  	animation:
		  		ripple-scale var(--ripple-duration) var(--ripple-timing),
		  		ripple-fade var(--ripple-duration) var(--ripple-timing);
		  	
		  }
		  
		  .${RadioGroupConfig.ITEM_INPUT}[type="radio"]:checked+.${RadioGroupConfig.ITEM_INPUT_CUSTOM}::before {
		  	border-radius: 50%;
		  }
		  
		  .${RadioGroupConfig.ITEM_INPUT}[type="checkbox"]:checked+.${RadioGroupConfig.ITEM_INPUT_CUSTOM}::before {
		  	border-radius: calc(var(--input-radius) / 2);
		  }
		  
		  .${RadioGroupConfig.ITEM_INPUT}[type="checkbox"]:checked+.${RadioGroupConfig.ITEM_INPUT_CUSTOM}::after {
		  	border-radius: calc(var(--input-radius) / 2);
		  }
		  
		  .${RadioGroupConfig.ITEM_INPUT}:checked~.${RadioGroupConfig.ITEM_CONTENT} {
		  	color: var(--primary);
		  }
		  
		  .${RadioGroupConfig.ITEM_BOTTM_BTN_BOX} {
			width:100%;
		  	margin: var(--gap);
		  	display: flex;
		  	flex-direction: row;
		  	align-items: center;
		  	justify-content: space-between;
		  	gap: var(--gap);
		  }
		  
		  @keyframes ripple-scale {
		  	to {
		  		transform: translate(-50%, -50%) scale(var(--ripple-scale));
		  	}
		  }
		  
		  @keyframes ripple-fade {
		  	to {
		  		opacity: 0;
		  	}
		  }
		  
		  /* 水波纹动画定义 */
		  @keyframes ripple {
		  	0% {
		  		transform: scale(0);
		  		opacity: 1;
		  	}
		  
		  	100% {
		  		transform: scale(2);
		  		opacity: 0;
		  	}
		  }
		  
		  /* 兼容性处理 */
		  @-webkit-keyframes ripple {
		  	0% {
		  		-webkit-transform: scale(0);
		  		opacity: 1;
		  	}
		  
		  	100% {
		  		-webkit-transform: scale(2);
		  		opacity: 0;
		  	}
		  }
		  
		`;
		document.head.appendChild(this.styleElement);
	}
}
